#!/bin/sh
#
# copySSHKey.sh
#

if [ $# != 5 ];then
  echo "Usage: copySSHKey.sh flag fromIp toIp username password"
  exit 1;
fi

flag=$1
fromip=$2
toip=$3
username=$4
password=$5

if [ $flag = "local" ];then
    expect -c "
	set timeout 5
	spawn su $username -c \" ssh-copy-id $username@$toip && echo right\"
	expect {
                \"right\" {
                        exit 0
                }
                \"Are you sure you want to continue connecting (yes/no)?\" {
                        send \"yes\n\"
                        expect \"$username@$toip's password:\" {
                                send \"$password\n\"
                                expect {
                                        default {
                                                exit 100
                                        }
                                        \"right\" {
                                                exit 0
                                        }
                                }
                        }
                }
                \"$username@$toip's password:\" {
                        send \"$password\n\"
                        expect {
                                default {
                                        exit 100
                                }
                                \"right\" {
                                        exit 0
                                }
                        }
                }
		\"Password:\" {
                        send \"$password\n\"
                        expect {
 				\"right\" {
				        exit 0
				}
				\"Are you sure you want to continue connecting (yes/no)?\" {
				        send \"yes\n\"
				        expect \"$username@$toip's password:\" {
				                send \"$password\n\"
				                expect {
				                        default {
				                                exit 100
				                        }
				                        \"right\" {
				                                exit 0
				                        }
				                }
				        }
				}
				\"$username@$toip's password:\" {
				        send \"$password\n\"
				        expect {
				                default {
				                        exit 100
				                }
				                \"right\" {
				                        exit 0
				                }
				        }
				}
                                default {
                                        exit 100
                                }
                        }
                }
                default {
                        exit 100
                }
        }
        interact"
fi

if [ $flag = "nolocal" ];then
    su $username -c " ssh $username@$fromip ./copySSHKey.sh local default $toip $username $password"
fi

if [ $? -ne 0 ]; then
	exit 100
fi

exit 0
